<template>
  <main class="main-container" v-loading="isLoading" :element-loading-text="loadingText">
    <div class="main-content">
      <div class="search-bar">
        <el-text>设备ID：</el-text>
        <el-select
          v-model="currentDeviceNode"
          class="device-select"
          filterable
          placeholder="请选择要查询的设备ID"
        >
          <el-option
            v-for="nodeId in nodeIds"
            :key="nodeId"
            :label="nodeId"
            :value="nodeId"
          ></el-option>
        </el-select>
      </div>
      <el-divider />
      <div class="reader-container">
        <div>
          <el-text>设备逻辑名：</el-text>
          <el-select style="margin-top: 4px" placeholder="请选择设备逻辑名" v-model="deviceName">
            <el-option
              v-for="typeItem in deviceNames"
              :key="typeItem"
              :value="typeItem"
              :label="typeItem"
            ></el-option>
          </el-select>
        </div>
        <div style="margin-top: 10px">
          <el-text>数据类型：</el-text>
          <el-select style="margin-top: 4px" placeholder="请选择数据类型" v-model="dataType">
            <el-option
              v-for="typeItem in dataTypes"
              :key="typeItem"
              :value="typeItem"
              :label="typeItem"
            ></el-option>
          </el-select>
        </div>
        <div style="margin-top: 10px">
          <el-text>设备点位地址：</el-text>
          <el-input
            style="margin-top: 4px"
            v-model="address"
            maxlength="15"
            placeholder="请输入设备点位地址"
            type="text"
          ></el-input>
        </div>
        <el-button
          style="width: 100%; margin-top: 10px"
          type="primary"
          @click="onReadAsync"
          :disabled="disabledReadButton"
        >
          读取数据
        </el-button>
        <div style="margin-top: 10px">
          <el-text>读取的数据值：</el-text>
          <el-input style="margin-top: 4px" v-model="readValue" type="text" readonly></el-input>
        </div>
      </div>
    </div>
  </main>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue';
import { DeviceServerClient } from '@/utils/device-server-client';
import { ElMessage } from 'element-plus';
import type { DeviceConfig } from '@/types/Device';
import { dataTypes } from '@/constants/device-server-client';
import { sleepAsync } from '@/utils/test-api';

const deviceName = ref('');
const dataType = ref('');
const address = ref('');
const readValue = ref('');

const isLoading = ref(false);
const currentDeviceNode = ref('');
const loadingText = ref('正在加载设备节点...');
const nodeIds = ref<string[]>([]);
const deviceConfigs = ref<DeviceConfig[]>([]);

const deviceNames = computed(() => {
  return deviceConfigs.value.map((item) => item.deviceName);
});

watch(currentDeviceNode, (newValue) => {
  if (newValue != null && newValue != undefined && newValue != '') {
    reloadDeviceConfigsAsync(newValue);
  }
});

const client = new DeviceServerClient(import.meta.env.VITE_DEVICE_SERVER_BASE_URL);

async function reloadDeviceIdsAsync() {
  loadingText.value = '正在加载设备节点...';
  isLoading.value = true;
  nodeIds.value = [];
  try {
    const result = await client.getIdsAsync();
    if (result.isSuccess) {
      if (result.result != null) {
        if (result.result.length == 0) {
          ElMessage.info('系统未添加设备节点！');
        }
        nodeIds.value = result.result ?? [];
      }
    } else {
      ElMessage.error(`加载设备节点错误,${result.message}`);
    }
  } catch (err) {
    ElMessage.error('加载设备节点错误！');
    console.error(err);
  } finally {
    isLoading.value = false;
  }
}

async function reloadDeviceConfigsAsync(nodeId: string) {
  loadingText.value = '正在加载设备节点配置...';
  isLoading.value = true;
  try {
    await sleepAsync(500);
    const result = await client.getDeviceConfigsAsync(nodeId);
    if (result.isSuccess) {
      deviceConfigs.value = result.result!;
    } else {
      ElMessage.error(`加载设备节点配置错误，${result.message}`);
    }
  } catch (err) {
    ElMessage.error('加载设备节点配置错误！');
    console.error(err);
  } finally {
    isLoading.value = false;
  }
}

const disabledReadButton = computed(() => {
  return deviceName.value == '' || dataType.value == '' || address.value == '';
});

async function onReadAsync() {
  isLoading.value = true;
  loadingText.value = '正在读取数据...';
  try {
    await sleepAsync(500);
    const result = await client.readValueAsync({
      deviceId: currentDeviceNode.value,
      task: {
        deviceName: deviceName.value,
        address: address.value,
        dataType: dataType.value
      }
    });

    if (result.isSuccess) {
      readValue.value = result.result;
      ElMessage.success('读取完成！');
    } else {
      ElMessage.error(result.message);
    }
  } catch (err) {
    console.error(err);
    ElMessage.error('读取数据时错误！');
  } finally {
    isLoading.value = false;
  }
}

onMounted(() => {
  reloadDeviceIdsAsync();
});
</script>

<style lang="scss" scoped>
:deep(.el-divider--horizontal) {
  margin: 15px 0px 0px 0px;
}

.main-container {
  height: 100%;
  width: 100%;
  padding: 0px 15px 15px;

  .main-content {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;

    .reader-container {
      height: 100%;
      margin-top: 15px;
    }

    .search-bar {
      display: flex;
      flex-direction: row;
      align-items: center;

      .device-select {
        width: 240px;
        margin-left: 10px;
      }
    }
  }
}
</style>